package com.candy.control;

import com.candy.service.LoginService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/userLogin",
        initParams ={ @WebInitParam(name = "initparam", value = "initparam")},
        loadOnStartup = 1)
public class UserLoginServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        String initparam= config.getInitParameter("initparam");
        System.out.println("获取在配置中的initparam的值：：："+initparam);
//       获取servletContext对象
        ServletContext context=  config.getServletContext();
        String contextParam =context.getInitParameter("contextparam");
        System.out.println("获取在配置中的contextParam的值：：："+contextParam);


    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        当请求为get请求时，则进行调用post方法进行处理
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//       创建一个Cookie对象
        Cookie userInfoCookie=new Cookie("userinfo","cookie信息");
        resp.addCookie(userInfoCookie);
//        获取客户端的所有cookie对象，返回cookie数组
        Cookie[] cookies=req.getCookies();
        for (Cookie coo:cookies
             ) {
            System.out.print("cookie名字:"+coo.getName()+"\t");
            System.out.print("cookie值:"+coo.getValue());
            System.out.println();
        }
        //接收前端传递过来的请求
        System.out.println("已接收到客户端发来的请求userservlet.....");
        //       首先处理字符集，避免中文乱码问题
//        req.setCharacterEncoding("UTF-8");
//        resp.setCharacterEncoding("UTF-8");
//        获取请求携带的参数
        String username= req.getParameter("username");
        String userpwd= req.getParameter("userpwd");
        System.out.println("前端传递过来的用户名：：：："+username);
        System.out.println("前端传递过来的密码：：：："+userpwd);
//        调用业务逻辑处理层，判断用户名密码是否匹配
        LoginService loginService=new LoginService();
//        接受业务逻辑处理结果
//        boolean ok=loginService.login(username,userpwd);
//        若结果为true，则跳转到登录页面
//        if(ok){
            //        将数据存放在请求域中
            req.setAttribute("username",username);
//        将数据存放在session
            req.getSession().setAttribute("role","vip");
//        转发，实现页面跳转
        req.getRequestDispatcher("welcome.jsp").forward(req,resp);
//        重定向
//            resp.sendRedirect("welcome.jsp");
//        }else {
////            反之则返回登录页面
//            req.getRequestDispatcher("login.jsp").forward(req,resp);
//        }








    }
}
